package com.darker.reggie.controller;

import com.darker.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是一个临时文件 需要转存到指定的位置 否则这次请求结束就会被删除
        //获取到原始的文件名  不建议使用 会使文件重名覆盖
        String originalFilename = file.getOriginalFilename();
        //从文件名中截取出文件的类型
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString()+suffix;
        File dir=new File(path);
        //判断当前路径的文件是否存在 不存在则创建
        if(!dir.exists()){
            dir.mkdirs();
        }
        log.info(path+filename);
        try {
            //将文件转存为指定路径
            file.transferTo(new File(path+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  R.success(filename);
    }
    //文件下载
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流 通过输入流 来读取文件
            FileInputStream fileInputStream=new FileInputStream(new File(path+name));
            //设置响应的类型=>图片
            response.setContentType("image/jpeg");
            //输出流  响应文件
            ServletOutputStream outputStream = response.getOutputStream();
            int len=0;
            byte[] bytes = new byte[1024];

            while((len=fileInputStream.read(bytes))!=-1){
                //写入
                outputStream.write(bytes,0,1024);
                //刷新
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
